package com.ruoyi.web.controller.util;

import io.minio.*;
import io.minio.http.Method;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.multipart.MultipartFile;

import java.io.InputStream;
import java.util.concurrent.TimeUnit;

@Component
public class MinioUtil {
    @Autowired
    private MinioClient minioClient;
    @Value("${minio.bucket}")
    private String bucketName;

    String policy = "{\n" +
            " \"Version\": \"2012-10-17\",\n" +
            " \"Statement\": [\n" +
            " {\n" +
            " \"Effect\": \"Allow\",\n" +
            " \"Principal\": \"*\",\n" +
            " \"Action\": [\"s3:GetObject\"],\n" +
            " \"Resource\": [\"arn:aws:s3:::" + bucketName + "/*\"]\n" +
            " }\n" +
            " ]\n" +
            "}";

    @RequestMapping("upload")
    public String upload(MultipartFile file, String objectName) throws
            Exception {
// 确保存储桶存在
        createBucket();
// 上传文件
        ObjectWriteResponse response = minioClient.putObject(
                PutObjectArgs.builder()
                        .bucket(bucketName)
                        .object(objectName)
                        .stream(file.getInputStream(), file.getSize(), -1)
                        .contentType(file.getContentType())
                        .build());
        System.out.println(response);
        String url = minioClient.getPresignedObjectUrl(
                GetPresignedObjectUrlArgs.builder()
                        .method(Method.GET)
                        .bucket(bucketName)
                        .object(objectName)
                        .expiry(1, TimeUnit.HOURS)
                        .build());
        System.out.println("Temp URL: " + url);
        return url;
    }

    public void createBucket() throws Exception {
        boolean found = minioClient.bucketExists(BucketExistsArgs.builder()
                .bucket(bucketName)
                .build());
        if (!found) {
// 设置存储桶策略为只读公开
            minioClient.setBucketPolicy(
                    SetBucketPolicyArgs.builder()
                            .bucket(bucketName)
                            .config(policy)
                            .build());
// minioClient.makeBucket(MakeBucketArgs.builder()
// .bucket(bucketName)
// .build());
        }
    }

    public InputStream downloadFile(String objectName) throws Exception {
        return minioClient.getObject(
                GetObjectArgs.builder()
                        .bucket(bucketName)
                        .object(objectName)
                        .build());
    }
}
